import { Component, OnInit, Inject, ViewChild, OnDestroy } from "@angular/core";
import { PLATFORM_ID, APP_ID } from "@angular/core";
import { isPlatformBrowser, isPlatformServer } from "@angular/common";
import { LocaleService, TranslationService, Language } from "angular-l10n";
import { Title } from "@angular/platform-browser";
import { Direction } from "@angular/cdk/bidi";
import { MatMenuTrigger } from "@angular/material";

import {
  ISelectSymbolResponse,
  IMu,
  IZi,
  IQuerySymbol
} from "@/trade/store/models/trade";

import { Store, select } from "@ngrx/store";
import * as fromUser from "@/user/store/reducers/index";
import * as fromRoot from "@/reducers/index";
import { map, filter, skip } from "rxjs/operators";
import { Subscription } from "rxjs";
import { UserActions } from "@/user/store/actions";
import { combineAll, debounceTime } from "rxjs/operators";
import { Router, CanActivate, ActivatedRoute } from "@angular/router";

@Component({
  selector: "app-my-menu",
  templateUrl: "./my-menu.component.html",
  styleUrls: ["./my-menu.component.scss"]
})
export class MyMenuComponent implements OnInit, OnDestroy {
  @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;

  lists: any[] = [
    {
      text: "user.common.my",
      type: "my"
    },
    {
      text: "user.logout",
      type: "logout"
    }
  ];

  show = false;

  user: any = {
    username: ""
  };

  user$ = this.store.pipe(
    select(fromRoot.user),
    filter(user => !!user)
  );

  sub$ = {
    userSub$: null
  };

  get starUsername() {
    const arr = this.user.username.split("");
    let j = 0;
    for (let i = 0; i < arr.length; i++) {
      if (i > 2 && i < arr.length - 3) {
        if (j >= 4) {
          arr.splice(i, 1, "");
        } else {
          arr.splice(i, 1, "*");
          ++j;
        }
      }
    }
    return arr.join("");
  }

  constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    public locale: LocaleService,
    public translation: TranslationService,
    public title: Title,
    @Inject("ConfigService") private configService,
    @Inject("PendingService") private pendingService,
    @Inject("UtilsService") private utilsService,
    private store: Store<fromUser.State | fromRoot.State>,
    public router: Router,
    activatedRoute: ActivatedRoute
  ) {}

  onMouseEnter(e) {
    this.show = true;
  }

  onMouseLeave(e) {
    this.show = false;
  }

  ngOnInit() {
    this.addListen();
  }

  addListen() {
    this.sub$.userSub$ = this.user$.subscribe(e => {
      this.user.username = e.username;
    });
  }

  onClickItem(e, item): void {
    if (item.type === "my") {
      this.router.navigate(["/u/my"]);
    }
    if (item.type === "logout") {
      this.logout();
    }
    this.show = false;
  }

  logout() {
    this.store.dispatch(new UserActions.Logout({ req: undefined, cpt: this }));
  }

  ngOnDestroy() {
    this.utilsService.unsub(this.sub$);
  }
}
